package br.senac.sp.persistence.test.example;

import br.senac.sp.persistence.AbstractPersistenceMapper;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class ComplexUserMapper extends AbstractPersistenceMapper<User, Long> {

    private static final String GET_OBJECT_FROM_STORAGE = "select * from USER where ID = ?";
    private final Connection connection;

    public ComplexUserMapper(Connection connection) {
        this.connection = connection;
    }

    @Override
    protected User getObjectFromStorage(Long id) {
        try {
            PreparedStatement statement = connection.prepareStatement(GET_OBJECT_FROM_STORAGE);
            statement.setLong(1, id);
            ResultSet result = statement.executeQuery();
            result.next();

            User user = new User();
            user.setId(id);
            user.setLogin(result.getString("LOGIN"));
            user.setName(result.getString("NAME"));

            return user;
        } catch (SQLException e) {
            throw new RuntimeException("Could not retrieve user from database.", e);
        }
    }

    @Override
    protected List<User> getObjectFromStorage() {
        throw new UnsupportedOperationException();
    }

    @Override
    protected void insertNewEntityInStorage(final User user) {
        throw new UnsupportedOperationException();
    }

    @Override
    protected void updateEntityInStorage(final User user) {
        throw new UnsupportedOperationException();
    }

    @Override
    protected void removeObjectFromStorage(final User user) {
        throw new UnsupportedOperationException();
    }

    @Override
    protected Long getIdFromObject(User user) {
        return user.getId();
    }
}
